package com.service.gmall.product.bloom.impl;

import com.service.gmall.product.bloom.BloomDataQueryService;
import com.service.gmall.product.bloom.BloomOpsService;
import com.service.gmall.product.service.SkuInfoService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author alpha
 * @className: BloomOpsServiceImpl
 * @date 2022/9/1 19:12
 * @Description
 */
@Service
public class BloomOpsServiceImpl implements BloomOpsService {
    @Autowired
    RedissonClient redissonClient;

    @Autowired
    SkuInfoService skuInfoService;


    @Override
    public void rebuildBloom(String bloomName, BloomDataQueryService bloomDataQueryService) {
        RBloomFilter<Object> oldbloomFilter = redissonClient.getBloomFilter(bloomName);
//        bloomFilter.delete();
        //1.使用新的布隆过滤器进行替换
        //1. 准备一个新的布隆过滤器
        String newBloomName = bloomName + "_bak";
        RBloomFilter<Object> bakBloomFilter = redissonClient.getBloomFilter(newBloomName);
        //2. 拿到所有的要保存的skuId
//        List<Long> allSkuId = skuInfoService.getAllSkuId();
        List list = bloomDataQueryService.queryData();
        //3. 初始化bloomFilter
        bakBloomFilter.tryInit(500000,0.00002);
        //3.1 添加值
//        for (Long skuId : allSkuId) {
//            bakBloomFilter.add(skuId);
//        }
        for (Object o : list) {
            bakBloomFilter.add(o);
        }
        //4. 交换bloomFilter使用中间变量
        oldbloomFilter.renameAsync("papapa");
        bakBloomFilter.renameAsync(bloomName);

        //5. 删除老布隆和中间变量
        oldbloomFilter.delete();
        RBloomFilter<Object> papapa = redissonClient.getBloomFilter("papapa");
        papapa.deleteAsync();

    }
}
